<?php

class Classes extends CI_Model {

	function __construct() {
		parent::__construct();
	}

	/**
	 * Add a single class to the database
	 * @return bool
	 */
	public function add_class( $data ) {

		// Check if class already exists
		if ( class_exists( $data['location'], $data['day'], $data['start_time'] ) ) {
			return false;
		}

		// Returns true on success
		if ( $this->db->insert('classes', $data) ) {
			return TRUE;
		} else {
			return FALSE;
		}	

	}

	/**
	 * Returns all information about a class/classes
	 * @param  class_id  (Optional)
	 * @return array
	 */
	public function get_class_data( $class_id = NULL ) {   
		// Fields to select
		$this->db->select('*');
		// Select from the classes table
		$this->db->from('classes');
		// Check if a class_id has been set, otherwise retrieve all classes
		if ( ! empty($class_id) ) {
		  $this->db->where('class_id', $class_id);
		}

		// Get results
		$query = $this->db->get();

		// If a class_id has been set return a row
		// Otherwise, return all rows
		if ( isset($class_id) ) {
		  $result = $query->row_array();
		  return $result;
		} else {
		  $result = $query->result_array();
		  return $result;
		}
	}

	/**
	 * Search for an existing class by location, day and start time of class (All parameters are optional)
	 * (Not specifying any paramaters will check if any classes exist)
	 */
	public function class_exists($location = null, $day = null, $start_time = null) {

		$this->db->select('class_id');
		$this->db->from('classes');

		if ( isset($location) ) {
		  $this->db->where('location', $location);
		}

		if ( isset($day) ) {
		  $this->db->where('day', $day);
		}

		if ( isset($start_time) ) {
		  $this->db->where('start_time', $start_time);
		}

		$query = $this->db->get();

		// Return true if any results found
		if ($query->num_rows() > 0) {
		  return TRUE;
		} else {
		  return FALSE;
		}

	}

	/**
	* Remove a class by class id
	* @param int $class_id 
	* @return bool
	*/
   public function remove_class($class_id) {
	  if ( $this->db->delete('classes', array('class_id' => $class_id) ) ) {
		return TRUE;
	  } else {
		return FALSE;
	  }
   }

}